from django.shortcuts import redirect
from django.urls import reverse

from commonTool.class_convert_tool import ClassConvertTool
from commonTool.logs.logs_wrapper import LogUtil
from page.application import const
from page.application.resp.loginVO import LoginVO

logs = LogUtil()


class LoginFilter:
    # 登录拦截模块
    LOGIN_INTERCEPTOR_URL = [
        # '/v1/app/index',
        # '/v1/app/account',
        '/v1/app',
    ]
    # 登录拦截排除接口
    LOGIN_INTERCEPTOR_EXCLUDE_URL = [
        '/v1/app/account/api/login',
        '/v1/app/account/login',
        '/v1/app/account/logout',
        '/v1/app/device/api/upgrade'
    ]

    def __init__(self, get_response):
        self.get_response = get_response

    @logs
    def __call__(self, request):
        logs.info("登录拦截器正在运行")
        # 获取当前请求的URL路径
        current_url = request.path

        # 判断是否需要拦截
        for exclude_url in self.LOGIN_INTERCEPTOR_EXCLUDE_URL:
            if current_url.find(exclude_url) != -1:
                logs.info(f"排除拦截接口:{current_url}")
                response = self.get_response(request)
                return response

        # 判断需要拦截的URL路径
        for url in self.LOGIN_INTERCEPTOR_URL:
            if current_url.startswith(url):
                user_json_str = request.session.get(const.SESSION_USER_KEY)
                if not user_json_str:
                    return redirect(reverse('login_page'))
                try:
                    user = ClassConvertTool.jsonConvertClass(user_json_str, LoginVO())
                    # logs.info("解析用户信息", user_json_str)
                except Exception as e:
                    logs.warning("登录拦截器异常:", e)

            response = self.get_response(request)
            return response
